home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / site.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  9.7 KB  |  305 lines

  1. #import sys
  2. #class AutoflushingStream:
  3. #    def __init__(self, stream):
  4. #        self.stream = stream
  5. #    def write(self, *args):
  6. #        self.stream.write(*args)
  7. #        self.stream.flush()
  8. #mylog = open("\\sitelog","wt")
  9. #sys.stdout = sys.stderr = AutoflushingStream(mylog)
  10. #print "this is sitelog; path now %s" % sys.path
  11.  
  12. """Customized site-setup script that leaves sys.path alone.
  13.  
  14. In a normal Python implementation, this module is automatically
  15. imported at startup, and sets up sys.path using various heuristics,
  16. and then does incidental other platform-dependent, heuristic-based
  17. initialization.
  18.  
  19. We want sys.path to be exactly one entry, so I've stripped out
  20. everything that has to do with augumenting sys.path and for the most
  21. part left the other incidental initializations alone. One exception to
  22. the first part of that sentence is that the logic for dealing with
  23. .pth files has been left alone, just in case.
  24.  
  25. In any event, this is the very first Python code that runs
  26. """
  27.  
  28. import sys
  29. import os
  30. import __builtin__
  31.  
  32. # Make up for the fact that it was probably (hopefully??!) impossible
  33. # to import the warnings module during Py_Initialize. Python is
  34. # designed to deal with this case and gracefully notice that it was
  35. # provided later.
  36. import warnings 
  37.  
  38. def makepath(*paths):
  39.     dir = os.path.abspath(os.path.join(*paths))
  40.     return dir, os.path.normcase(dir)
  41.  
  42. def abs__file__():
  43.     """Set all module' __file__ attribute to an absolute path"""
  44.     for m in sys.modules.values():
  45.         try:
  46.             m.__file__ = os.path.abspath(m.__file__)
  47.         except AttributeError:
  48.             continue
  49.  
  50. def removeduppaths():
  51.     """ Remove duplicate entries from sys.path along with making them
  52.     absolute"""
  53.     # This ensures that the initial path provided by the interpreter contains
  54.     # only absolute pathnames, even if we're running from the build directory.
  55.     L = []
  56.     known_paths = set()
  57.     for dir in sys.path:
  58.         # Filter out duplicate paths (on case-insensitive file systems also
  59.         # if they only differ in case); turn relative paths into absolute
  60.         # paths.
  61.         dir, dircase = makepath(dir)
  62.         if not dircase in known_paths:
  63.             L.append(dir)
  64.             known_paths.add(dircase)
  65.     sys.path[:] = L
  66.     return known_paths
  67.  
  68. def _init_pathinfo():
  69.     """Return a set containing all existing directory entries from sys.path"""
  70.     d = set()
  71.     for dir in sys.path:
  72.         try:
  73.             if os.path.isdir(dir):
  74.                 dir, dircase = makepath(dir)
  75.                 d.add(dircase)
  76.         except TypeError:
  77.             continue
  78.     return d
  79.  
  80. def addpackage(sitedir, name, known_paths):
  81.     """Add a new path to known_paths by combining sitedir and 'name' or execute
  82.     sitedir if it starts with 'import'"""
  83.     if known_paths is None:
  84.         _init_pathinfo()
  85.         reset = 1
  86.     else:
  87.         reset = 0
  88.     fullname = os.path.join(sitedir, name)
  89.     try:
  90.         f = open(fullname, "rU")
  91.     except IOError:
  92.         return
  93.     try:
  94.         for line in f:
  95.             if line.startswith("#"):
  96.                 continue
  97.             if line.startswith("import"):
  98.                 exec line
  99.                 continue
  100.             line = line.rstrip()
  101.             dir, dircase = makepath(sitedir, line)
  102.             if not dircase in known_paths and os.path.exists(dir):
  103.                 sys.path.append(dir)
  104.                 known_paths.add(dircase)
  105.     finally:
  106.         f.close()
  107.     if reset:
  108.         known_paths = None
  109.     return known_paths
  110.  
  111. def addsitedir(sitedir, known_paths=None):
  112.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  113.     'sitedir'"""
  114.     if known_paths is None:
  115.         known_paths = _init_pathinfo()
  116.         reset = 1
  117.     else:
  118.         reset = 0
  119.     sitedir, sitedircase = makepath(sitedir)
  120.     if not sitedircase in known_paths:
  121.         sys.path.append(sitedir)        # Add path component
  122.     try:
  123.         names = os.listdir(sitedir)
  124.     except os.error:
  125.         return
  126.     names.sort()
  127.     for name in names:
  128.         if name.endswith(os.extsep + "pth"):
  129.             addpackage(sitedir, name, known_paths)
  130.     if reset:
  131.         known_paths = None
  132.     return known_paths
  133.  
  134.  
  135. def setquit():
  136.     """Define new built-ins 'quit' and 'exit'.
  137.     These are simply strings that display a hint on how to exit.
  138.  
  139.     """
  140.     if os.sep == ':':
  141.         exit = 'Use Cmd-Q to quit.'
  142.     elif os.sep == '\\':
  143.         exit = 'Use Ctrl-Z plus Return to exit.'
  144.     else:
  145.         exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  146.     __builtin__.quit = __builtin__.exit = exit
  147.  
  148.  
  149. class _Printer(object):
  150.     """interactive prompt objects for printing the license text, a list of
  151.     contributors and the copyright notice."""
  152.  
  153.     MAXLINES = 23
  154.  
  155.     def __init__(self, name, data, files=(), dirs=()):
  156.         self.__name = name
  157.         self.__data = data
  158.         self.__files = files
  159.         self.__dirs = dirs
  160.         self.__lines = None
  161.  
  162.     def __setup(self):
  163.         if self.__lines:
  164.             return
  165.         data = None
  166.         for dir in self.__dirs:
  167.             for filename in self.__files:
  168.                 filename = os.path.join(dir, filename)
  169.                 try:
  170.                     fp = file(filename, "rU")
  171.                     data = fp.read()
  172.                     fp.close()
  173.                     break
  174.                 except IOError:
  175.                     pass
  176.             if data:
  177.                 break
  178.         if not data:
  179.             data = self.__data
  180.         self.__lines = data.split('\n')
  181.         self.__linecnt = len(self.__lines)
  182.  
  183.     def __repr__(self):
  184.         self.__setup()
  185.         if len(self.__lines) <= self.MAXLINES:
  186.             return "\n".join(self.__lines)
  187.         else:
  188.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  189.  
  190.     def __call__(self):
  191.         self.__setup()
  192.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  193.         lineno = 0
  194.         while 1:
  195.             try:
  196.                 for i in range(lineno, lineno + self.MAXLINES):
  197.                     print self.__lines[i]
  198.             except IndexError:
  199.                 break
  200.             else:
  201.                 lineno += self.MAXLINES
  202.                 key = None
  203.                 while key is None:
  204.                     key = raw_input(prompt)
  205.                     if key not in ('', 'q'):
  206.                         key = None
  207.                 if key == 'q':
  208.                     break
  209.  
  210. def setcopyright():
  211.     """Set 'copyright' and 'credits' in __builtin__"""
  212.     __builtin__.copyright = _Printer("copyright", sys.copyright)
  213.     if sys.platform[:4] == 'java':
  214.         __builtin__.credits = _Printer(
  215.             "credits",
  216.             "Jython is maintained by the Jython developers (www.jython.org).")
  217.     else:
  218.         __builtin__.credits = _Printer("credits", """\
  219.     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  220.     for supporting Python development.  See www.python.org for more information.""")
  221.     here = os.path.dirname(os.__file__)
  222.     __builtin__.license = _Printer(
  223.         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  224.         ["LICENSE.txt", "LICENSE"],
  225.         [os.path.join(here, os.pardir), here, os.curdir])
  226.  
  227.  
  228. class _Helper(object):
  229.     """This normally handles the built-in 'help', but here it's stubbed
  230. out to avoid pulling in pydoc."""
  231.     def __repr__(self):
  232.         return "Help not available."
  233.     def __call__(self, *args, **kwds):
  234.         return "Help not available."
  235.  
  236. def sethelper():
  237.     __builtin__.help = _Helper()
  238.  
  239. def aliasmbcs():
  240.     """On Windows, some default encodings are not provided by Python,
  241.     while they are always available as "mbcs" in each locale. Make
  242.     them usable by aliasing to "mbcs" in such a case."""
  243.     if sys.platform == 'win32':
  244.         import locale, codecs
  245.         enc = locale.getdefaultlocale()[1]
  246.         if enc.startswith('cp'):            # "cp***" ?
  247.             try:
  248.                 codecs.lookup(enc)
  249.             except LookupError:
  250.                 import encodings
  251.                 encodings._cache[enc] = encodings._unknown
  252.                 encodings.aliases.aliases[enc] = 'mbcs'
  253.  
  254. def setencoding():
  255.     """Set the string encoding used by the Unicode implementation.  The
  256.     default is 'ascii', but if you're willing to experiment, you can
  257.     change this."""
  258.     encoding = "utf-8" # The character set of the Democracy log file
  259.     if 0:
  260.         # Enable to support locale aware default string encodings.
  261.         import locale
  262.         loc = locale.getdefaultlocale()
  263.         if loc[1]:
  264.             encoding = loc[1]
  265.     if 0:
  266.         # Enable to switch off string to Unicode coercion and implicit
  267.         # Unicode to string conversion.
  268.         encoding = "undefined"
  269.     if encoding != "ascii":
  270.         # On Non-Unicode builds this will raise an AttributeError...
  271.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  272.  
  273. def execsitecustomize():
  274.     """Run custom site specific code, if available."""
  275.     try:
  276.         import sitecustomize
  277.     except ImportError:
  278.         pass
  279.  
  280. def main():
  281.     abs__file__()
  282.     paths_in_sys = removeduppaths()
  283.     setquit()
  284.     setcopyright()
  285.     sethelper()
  286.     aliasmbcs()
  287.     setencoding()
  288.     execsitecustomize()
  289.     # Remove sys.setdefaultencoding() so that users cannot change the
  290.     # encoding after initialization.  The test for presence is needed when
  291.     # this module is run as a script, because this code is executed twice.
  292.     if hasattr(sys, "setdefaultencoding"):
  293.         del sys.setdefaultencoding
  294.  
  295. main()
  296.  
  297. def _test():
  298.     print "sys.path = ["
  299.     for dir in sys.path:
  300.         print "    %r," % (dir,)
  301.     print "]"
  302.  
  303. if __name__ == '__main__':
  304.     _test()
  305.